package cn.tsingyu.spring.example.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.tsingyu.spring.example.entity.User;
import cn.tsingyu.spring.example.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	@RequestMapping(value="doLogin.html")
	public String doLogin(HttpServletRequest request){
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = userService.getUser(username, password);
		if(user.getUserId()!=0){
			return "hello";
		}else{
			return "login";
		}
		
	}
	
	/**
	 * 用户登录
	 * @param user
	 * @param request
	 * @return
	 */
	@RequestMapping("/login.html")
	public String login(User user,HttpServletRequest request){
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try{
			subject.login(token);
			Session session=subject.getSession();
			session.setAttribute("user", user);
			return "redirect:/";
		}catch(Exception e){
			e.printStackTrace();
			request.setAttribute("user", user);
			request.setAttribute("errorMsg", "用户名或密码错误！");
			return "login";
		}
	}
	
	@RequestMapping("/")
	public String main(){
		Subject subject=SecurityUtils.getSubject();
		Session session=subject.getSession();
		if(session.getAttribute("user")!=null&&session.getAttribute("user")!=""){
			return "system/index/main";
		}
		return "login";
		
	}
	/**
	 * 进入tab标签
	 * @return
	 */
	@RequestMapping(value="/tab")
	public String tab(){
		return "system/index/tab";
	}
	
	/**
	 * 进入首页后的默认页面
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/login_default")
	public ModelAndView defaultPage() throws Exception{
		ModelAndView mv = new ModelAndView();
		mv.setViewName("system/index/default");
		return mv;
	}
	
	/**
	 * 用户注销
	 */
	@RequestMapping(value="/logout")
	public String logout(){
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject(); 
		Session session=subject.getSession();
		session.removeAttribute("user");
		subject.logout();
		return "login";
	}
}
